package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import com.sun.tools.corba.se.idl.InterfaceGen;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/*
    ヾ(❀ﾟ▽ﾟ)ノ 
 
 Grey1996year@163.com 
 
*/
@RestController
@RequestMapping("/role")
public class RoleController {

	@Reference
	private RoleService roleService;


	@RequestMapping("/findAll")
	public PageResult findAll(@RequestBody QueryPageBean queryPageBean) {

		try {
			PageResult PageResult =  roleService.findAll(queryPageBean);
			return PageResult;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}


	@RequestMapping("/findPermAndMenu")
	public Result findPermAndMenu() {

		try {
			Map<String,Object> map =  roleService.findPermAndMenu();


			return new Result(true,"",map);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,"");
		}
	}
	@RequestMapping("/findById")
	public Result findById(Integer id) {

		try {
			Role role =  roleService.findById(id);

			List<Integer> list_perm = new ArrayList<>();
			Set<Permission> permissions = role.getPermissions();
			for (Permission permission : permissions) {
				Integer permissionId = permission.getId();
				list_perm.add(permissionId);
			}
			//
			List<Integer> list_menu = new ArrayList<>();
			LinkedHashSet<Menu> menus = role.getMenus();
			for (Menu menu : menus) {
				Integer menuId = menu.getId();
				list_menu.add(menuId);
			}
			Map<String,Object> map = new HashMap<>();
			map.put("role",role);
			map.put("permissionId",list_perm);
			map.put("menuId",list_menu);

			return new Result(true,"",map);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,"");
		}
	}

	@RequestMapping("/edit")
	public Result edit(@RequestBody Role role,Integer[] permissionIds,Integer[] menuIds) {

		try {
			 roleService.update(role,permissionIds,menuIds);


			return new Result(true,"");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,"");
		}
	}

	@RequestMapping("/add")
	public Result add(@RequestBody Role role,Integer[] permissionIds,Integer[] menuIds) {

		try {
			roleService.add(role,permissionIds,menuIds);


			return new Result(true,"");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,"");
		}
	}

	@RequestMapping("/delete")
	public Result delete(Integer id) {

		try {
			roleService.delete(id);


			return new Result(true,"");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false,"");
		}
	}



}
